/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jifConsultarOrden.java
 *
 * Created on 21-jul-2010, 7:48:33
 */

package Ordenes;

import Proveedores.jifAdministrarProveedor;
import administracion.delegate.GestionPedidosDelegate;
import administracion.helper.Listas;
import administracion.helper.MiTablePrint;

import administracion.helper.Reportes;
import administracion.helper.Utiles_MensajesDialogo;
import administracion.helper.jPaginacion;
import com.jidesoft.hints.ListDataIntelliHints;
import GUI.SuministrosPrincipal;
import java.awt.BorderLayout;
import java.awt.Frame;

import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import org.jdesktop.beansbinding.AutoBinding;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.beansbinding.ELProperty;
import org.jdesktop.swingbinding.JTableBinding;
import org.jdesktop.swingbinding.SwingBindings;
import suministros.ejb30.TO.AnoTO;
import suministros.ejb30.TO.EmpresaTO;
import suministros.ejb30.TO.MesTO;
import suministros.ejb30.TO.OrdenTO;
import suministros.ejb30.TO.ParametrosConsultaTO;
import suministros.ejb30.TO.ProveedorTO;
import suministros.ejb30.TO.TipoTO;
import suministros.ejb30.TO.ZonaTO;
import suministros.ejb30.helper.EmailVacioException;

/**
 *
 * @author Luis_Angel
 */
public class jifConsultarOrden extends javax.swing.JInternalFrame implements Observer {

  
    private ListDataIntelliHints intelliHintsProveedor;
    private JTableBinding jTableBinding;
    private int id_tipo_orden;
    private List<OrdenTO> ordenes_encontradas;
    private SuministrosPrincipal dsk_padre;
    private  jPaginacion panelPaginacion;
    private ParametrosConsultaTO params;
    /** Creates new form jifConsultarOrden */
    public jifConsultarOrden(String titulo,boolean isAdministra,SuministrosPrincipal dsk_padre) {
        super(titulo);
        this.panelPaginacion = new jPaginacion(this,15);
        initComponents();
        List empresass = Listas.getEmpresas();
        if(empresass.isEmpty()){
            this.jCheckBox1.setEnabled(false);
        }
        try {
            cargaHintsIndependientes();
        } catch (Exception ex) {
            Logger.getLogger(jifAdministrarProveedor.class.getName()).log(Level.SEVERE, null, ex);
        }

         try {
            Listas.cargarAnosMeses();
        } catch (Exception e) {
            Utiles_MensajesDialogo.mensajeError("Error al cargar Años");
        }
        llenarComboZona();
        llenarComboAno();
        llenarComboEmpresa();
        llenarComboTipoOrden();
         this.id_tipo_orden = ((TipoTO)this.jcboTipoOrden.getSelectedItem()).getId_tabla_tipo();
         this.jbAnular.setVisible(isAdministra);
         this.jbModificar.setVisible(isAdministra);
         this.jbFinalizar.setVisible(isAdministra);
         this.dsk_padre=dsk_padre;
         
    }


    private void cargaHintsIndependientes() throws Exception {
         this.intelliHintsProveedor = new ListDataIntelliHints(this.jtfRazon,Listas.getProveedores());
    }

     private void llenarComboZona() {
        List listaZonas = null;
        List listaZonas_cbo = this.cboBeanBindingZona1.getLista();
        listaZonas_cbo.clear();
        try
        {
          listaZonas = Listas.getZonas();
          this.cboBeanBindingZona1.setLista(listaZonas);
          this.bindingGroup.bind();
          this.jcboZona.updateUI();
          this.jcboZona.setSelectedIndex(-1);
        } catch (Exception ex) {
          Utiles_MensajesDialogo.mensajeAlerta("Error al obtener zonas\n" + ex.getMessage());
          ex.printStackTrace();
          
        }
   }
      private void llenarComboEmpresa() {
        List empresas = null;
        List listaPaises_cbo = this.cboBeanBindingEmpresa1.getLista();
        listaPaises_cbo.clear();
        try
        {
          if(this.jCheckBox1.isSelected()){
                empresas = Listas.getEmpresas();
            }
            else{
                empresas = Listas.getEmpresaPrincipal();
            }
          this.cboBeanBindingEmpresa1.setLista(empresas);
          this.bindingGroup.bind();
          this.jcbEmpresa.updateUI();
          this.jcbEmpresa.setSelectedIndex(0);
        } catch (Exception ex) {
          Utiles_MensajesDialogo.mensajeAlerta("Error al obtener empresas\n" + ex.getMessage());
          ex.printStackTrace();

        }
      }


      private void llenarComboTipoOrden() {
        List listaTipos1 = null;
        List listaTipos_cbo1 = this.cboBeanBindingTipo1.getLista();
        listaTipos_cbo1.clear();
        try
        {
          listaTipos1 = Listas.getTipo_porTabla("tipo_Orden");

          this.cboBeanBindingTipo1.setLista(listaTipos1);
          this.bindingGroup.bind();
          this.jcboTipoOrden.updateUI();
          this.jcboTipoOrden.setSelectedIndex(0);
        } catch (Exception ex) {
          Utiles_MensajesDialogo.mensajeAlerta("Error al obtener Tipos de orden\n" + ex.getMessage());
          ex.printStackTrace();
          Logger.getLogger(jifRegistrarOrdenCompra.class.getName()).log(Level.SEVERE, null, ex);
        }
      }


      private ParametrosConsultaTO getParametrosConsulta(){
          String zona = null;
        String anio = null;
        String mes = null;
        String ruc = null;
        String orden = null;
        String id_empresa= null;
        if(this.jcbEmpresa.getSelectedIndex()>=0)
             id_empresa = ((EmpresaTO)this.jcbEmpresa.getSelectedItem()).getCodigo();
        if(this.jcboZona.getSelectedIndex()>=0)
             zona =((ZonaTO)this.jcboZona.getSelectedItem()).getId_zona();
        if(this.jcboAno.getSelectedIndex()>=0)
             anio = ((AnoTO)this.jcboAno.getSelectedItem()).getAno();
        if(this.jcboMes.getSelectedIndex()>=0)
             mes = ((MesTO)this.jcboMes.getSelectedItem()).getMes();
        if(this.jtfRuc.getText().trim().length()>0)
             ruc = this.jtfRuc.getText().trim();
        if(this.jtfNroOrden.getText().trim().length()>0)
             orden = this.jtfNroOrden.getText().trim();
       
            ParametrosConsultaTO parametros = new ParametrosConsultaTO();
            parametros.setAnio(anio);
            parametros.setMes(mes);
            parametros.setId_zona(zona);
            parametros.setRuc_proveedor(ruc);
            parametros.setId_empresa(id_empresa);
            parametros.setNro_orden(orden);
             return parametros;
        }

    public void update(Observable o, Object arg) {
        buscarOrdenes();
    }
      

      /*class ActionAtras implements ActionListener{

        public void actionPerformed(ActionEvent e) {
            paginacion.anterior();
            buscarOrdenes(params);
        }

      }

       class ActionSiguiente implements ActionListener{

        public void actionPerformed(ActionEvent e) {
            paginacion.siguiente();
            buscarOrdenes(params);
        }

      }*/



     private void buscarOrdenes(){

          try {
             
            ordenes_encontradas = GestionPedidosDelegate.getInstance().consultarOrden(params,this.id_tipo_orden,this.panelPaginacion.getPagActual(),this.panelPaginacion.getPagTamano());
          // vo.setNum_actual(ordenes_encontradas.size());
           
            actualizaTablaDetallesSolicitud(ordenes_encontradas);
            if(ordenes_encontradas.isEmpty()){
                 this.jbDetalles.setEnabled(false);
                 this.jbComprobante.setEnabled(false);
                 this.jbAnular.setEnabled(false);
                 this.jbFinalizar.setEnabled(false);
                 this.jbModificar.setEnabled(false);
                 this.jbEnvio.setEnabled(false);
            }
               
            else{
                this.jbDetalles.setEnabled(true);
                this.jbComprobante.setEnabled(true);
                this.jbAnular.setEnabled(true);
                this.jbModificar.setEnabled(true);
                this.jbEnvio.setEnabled(true);
                this.jbFinalizar.setEnabled(true);
            }
                
        } catch (Exception ex) {
            Logger.getLogger(jifConsultarOrden.class.getName()).log(Level.SEVERE, null, ex);
        }

     }

      private void actualizaTablaDetallesSolicitud(List<OrdenTO> ordenes_encontradas) {
            this.bindingGroup = new BindingGroup();
            this.jTableBinding = SwingBindings.createJTableBinding(AutoBinding.UpdateStrategy.READ,ordenes_encontradas , this.jtOrdenes);

            JTableBinding.ColumnBinding columnBinding0 = this.jTableBinding.addColumnBinding(ELProperty.create("${nroOrden}"));

            columnBinding0.setColumnName("Nro Orden");
            columnBinding0.setColumnClass(String.class);
            columnBinding0.setEditable(false);

            JTableBinding.ColumnBinding columnBinding1= this.jTableBinding.addColumnBinding(ELProperty.create("${fecha_emision}"));

            columnBinding1.setColumnName("Fecha de Emision");
            columnBinding1.setColumnClass(String.class);
            columnBinding1.setEditable(false);


            JTableBinding.ColumnBinding columnBinding2 = this.jTableBinding.addColumnBinding(ELProperty.create("${zona}"));

            columnBinding2.setColumnName("Zona");
            columnBinding2.setColumnClass(String.class);
            columnBinding2.setEditable(false);

            JTableBinding.ColumnBinding columnBinding3 = this.jTableBinding.addColumnBinding(ELProperty.create("${valor_total}"));

            columnBinding3.setColumnName("Monto");
            columnBinding3.setColumnClass(BigDecimal.class);
            columnBinding3.setEditable(false);

            JTableBinding.ColumnBinding columnBinding4 = this.jTableBinding.addColumnBinding(ELProperty.create("${ruc_proveedor}"));

            columnBinding4.setColumnName("RUC");
            columnBinding4.setColumnClass(String.class);
            columnBinding4.setEditable(false);

            JTableBinding.ColumnBinding columnBinding5 = this.jTableBinding.addColumnBinding(ELProperty.create("${descripcion_estado}"));

            columnBinding5.setColumnName("Estado");
            columnBinding5.setColumnClass(String.class);
            columnBinding5.setEditable(false);

            this.bindingGroup.addBinding(this.jTableBinding);
            this.bindingGroup.bind();

           /* int[] porcentajes= {15,15,15,15,15,15};
            try {
                Utiles_Tabla.definirAnchoColumnasJTable(jtOrdenes, porcentajes);
            } catch (Exception ex) {
                Logger.getLogger(jdAdministrarLicitacion.class.getName()).log(Level.SEVERE, null, ex);
            }*/
                //MiTablePrint.autoSizeTableColumns(this.jtOrdenes);

        }

    private void llenarComboAno()
      {
        List listaAnos = null;
        List listaAnos_cbo = this.cboBeanBindingAno1.getLista();
        listaAnos_cbo.clear();
        try
        {
          listaAnos = Listas.getAnos();
          this.cboBeanBindingAno1.setLista(listaAnos);
          this.bindingGroup.bind();
          this.jcboAno.updateUI();
          this.jcboAno.setSelectedIndex(-1);
        } catch (Exception ex) {
          Utiles_MensajesDialogo.mensajeAlerta("Error al obtener años\n" + ex.getMessage());
          ex.printStackTrace();

        }
      }

  private void llenarComboMes() {
    List listaMeses = null;
    List listaMeses_cbo = this.cboBeanBindingMes1.getLista();
    listaMeses_cbo.clear();
    try {
      if (this.jcboAno.getSelectedItem() != null) {
        AnoTO an = (AnoTO)this.jcboAno.getSelectedItem();
        listaMeses = Listas.getMesesAno(an);
        this.cboBeanBindingMes1.setLista(listaMeses);
        this.bindingGroup.bind();
        this.jcboMes.updateUI();
        this.jcboMes.setSelectedIndex(0);
      }
    } catch (Exception ex) {
      Utiles_MensajesDialogo.mensajeAlerta("Error al obtener meses\n" + ex.getMessage());
      ex.printStackTrace();
      
    }
  }

  private void buscarRazonSocial()
      {
        ProveedorTO pro;
        if (this.jtfRuc.getText().trim().length() < 1) {
              try { pro = (ProveedorTO)this.intelliHintsProveedor.getSelectedHint();
              } catch (NullPointerException ex) {
                pro = null;
              }
            }
        else {
          pro = Listas.getProveedorcodigo(this.jtfRuc.getText().trim());
        }
        if (pro == null) {
          Utiles_MensajesDialogo.mensajeError("El proveedor no existe!");
          this.jtfRuc.setText("");
          pro = null;
        }
        else {

          this.jtfRazon.setText(pro.getRazon() + " - " + pro.getCodProveedor());
          this.jtfRuc.setText(pro.getCodProveedor());
          buscar();
        }

      }

  private void buscar(){
       try
        {
           params = getParametrosConsulta();
           int num_ordenes_encontradas = GestionPedidosDelegate.getInstance().getNumeroDeOrdenes(params, id_tipo_orden);
           panelPaginacion.setTotalResultados(num_ordenes_encontradas);
        }
        catch (Exception e) {
            Utiles_MensajesDialogo.mensajeError(e.getMessage());
        }
  }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        cboBeanBindingMes1 = new administracion.BeanBinding.CboBeanBindingMes();
        cboBeanBindingZona1 = new administracion.BeanBinding.CboBeanBindingZona();
        cboBeanBindingAno1 = new administracion.BeanBinding.CboBeanBindingAno();
        cboBeanBindingTipo1 = new administracion.BeanBinding.CboBeanBindingTipo();
        cboBeanBindingEmpresa1 = new administracion.BeanBinding.CboBeanBindingEmpresa();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtOrdenes = new javax.swing.JTable();
        this.jtOrdenes.getTableHeader().setReorderingAllowed(false) ;
        jpOperativo = new javax.swing.JPanel();
        Mes = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jcboMes = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jcboZona = new javax.swing.JComboBox();
        jbBuscar = new javax.swing.JButton();
        jtfRazon = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        jcboAno = new javax.swing.JComboBox();
        jtfRuc = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jcboTipoOrden = new javax.swing.JComboBox();
        jcbEmpresa = new javax.swing.JComboBox();
        jLabel20 = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jtfNroOrden = new javax.swing.JTextField();
        jLabel19 = new javax.swing.JLabel();
        jbCancelar = new javax.swing.JButton();
        jbDetalles = new javax.swing.JButton();
        jbAnular = new javax.swing.JButton();
        jbModificar = new javax.swing.JButton();
        jbComprobante = new javax.swing.JButton();
        jbEnvio = new javax.swing.JButton();
        jbtImprimir = new javax.swing.JButton();
        jbFinalizar = new javax.swing.JButton();

        setIconifiable(true);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Ordenes Encontradas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12), java.awt.Color.blue)); // NOI18N
        jPanel1.setLayout(new java.awt.BorderLayout());
        jPanel1.add(panelPaginacion,BorderLayout.NORTH);

        jtOrdenes.setAutoCreateRowSorter(true);
        jtOrdenes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nro Orden", "Fecha Emision", "Zona", "Monto", "RUC"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Double.class, java.lang.Object.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jtOrdenes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jtOrdenes);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jpOperativo.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Busqueda Avanzada", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12), java.awt.Color.blue)); // NOI18N

        Mes.setFont(new java.awt.Font("Arial", 1, 12));
        Mes.setText("Mes");

        jLabel2.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel2.setText("Año");

        jcboMes.setFont(new java.awt.Font("Arial", 0, 12));

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${lista}");
        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cboBeanBindingMes1, eLProperty, jcboMes);
        bindingGroup.addBinding(jComboBoxBinding);

        jcboMes.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jcboMesKeyPressed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel3.setText("SUCURSAL");

        jcboZona.setFont(new java.awt.Font("Arial", 0, 12));

        eLProperty = org.jdesktop.beansbinding.ELProperty.create("${lista}");
        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cboBeanBindingZona1, eLProperty, jcboZona);
        bindingGroup.addBinding(jComboBoxBinding);

        jcboZona.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jcboZonaKeyPressed(evt);
            }
        });

        jbBuscar.setFont(new java.awt.Font("Arial", 0, 12));
        jbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/find.png"))); // NOI18N
        jbBuscar.setMnemonic('B');
        jbBuscar.setText("Buscar");
        jbBuscar.setToolTipText("Cancelar la Operacion");
        jbBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbBuscarActionPerformed(evt);
            }
        });
        jbBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbBuscarKeyPressed(evt);
            }
        });

        jtfRazon.setFont(new java.awt.Font("Arial", 0, 12));
        jtfRazon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfRazonActionPerformed(evt);
            }
        });
        jtfRazon.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtfRazonKeyPressed(evt);
            }
        });

        jLabel9.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/user.png"))); // NOI18N
        jLabel9.setText("PROVEEDOR");

        jLabel18.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel18.setText("RUC");

        jcboAno.setFont(new java.awt.Font("Arial", 0, 12));

        eLProperty = org.jdesktop.beansbinding.ELProperty.create("${lista}");
        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cboBeanBindingAno1, eLProperty, jcboAno);
        bindingGroup.addBinding(jComboBoxBinding);

        jcboAno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcboAnoActionPerformed(evt);
            }
        });
        jcboAno.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jcboAnoKeyPressed(evt);
            }
        });

        jtfRuc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfRucActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel4.setText("TIPO");

        eLProperty = org.jdesktop.beansbinding.ELProperty.create("${lista}");
        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cboBeanBindingTipo1, eLProperty, jcboTipoOrden);
        bindingGroup.addBinding(jComboBoxBinding);

        jcboTipoOrden.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcboTipoOrdenItemStateChanged(evt);
            }
        });

        jcbEmpresa.setEnabled(false);

        eLProperty = org.jdesktop.beansbinding.ELProperty.create("${lista}");
        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cboBeanBindingEmpresa1, eLProperty, jcbEmpresa);
        bindingGroup.addBinding(jComboBoxBinding);

        jLabel20.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel20.setText("EMPRESA");

        jCheckBox1.setFont(new java.awt.Font("Arial", 1, 12));
        jCheckBox1.setText("OTRAS EMPRESAS");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jtfNroOrden.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfNroOrdenActionPerformed(evt);
            }
        });

        jLabel19.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel19.setText("Nº ORDEN");

        javax.swing.GroupLayout jpOperativoLayout = new javax.swing.GroupLayout(jpOperativo);
        jpOperativo.setLayout(jpOperativoLayout);
        jpOperativoLayout.setHorizontalGroup(
            jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpOperativoLayout.createSequentialGroup()
                .addGap(3, 3, 3)
                .addComponent(jCheckBox1)
                .addGap(18, 18, 18)
                .addComponent(jLabel20)
                .addGap(4, 4, 4)
                .addComponent(jcbEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addComponent(jLabel4)
                .addGap(10, 10, 10)
                .addComponent(jcboTipoOrden, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jpOperativoLayout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(jLabel18)
                .addGap(16, 16, 16)
                .addComponent(jtfRuc, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addComponent(jLabel9)
                .addGap(10, 10, 10)
                .addComponent(jtfRazon, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jpOperativoLayout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(jLabel19)
                .addGap(5, 5, 5)
                .addComponent(jtfNroOrden, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(4, 4, 4)
                .addComponent(jLabel3)
                .addGap(10, 10, 10)
                .addComponent(jcboZona, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20)
                .addComponent(jLabel2)
                .addGap(4, 4, 4)
                .addComponent(jcboAno, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addComponent(Mes)
                .addGap(4, 4, 4)
                .addComponent(jcboMes, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jpOperativoLayout.createSequentialGroup()
                .addGap(252, 252, 252)
                .addComponent(jbBuscar))
        );
        jpOperativoLayout.setVerticalGroup(
            jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpOperativoLayout.createSequentialGroup()
                .addGroup(jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jCheckBox1)
                    .addGroup(jpOperativoLayout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(jLabel20))
                    .addGroup(jpOperativoLayout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jcbEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpOperativoLayout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jLabel4))
                    .addComponent(jcboTipoOrden, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel18)
                    .addComponent(jtfRuc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addGroup(jpOperativoLayout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(jtfRazon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(6, 6, 6)
                .addGroup(jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpOperativoLayout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jLabel19))
                    .addGroup(jpOperativoLayout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jtfNroOrden, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpOperativoLayout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel3))
                    .addComponent(jcboZona, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jpOperativoLayout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel2))
                    .addComponent(jcboAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jpOperativoLayout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(Mes))
                    .addComponent(jcboMes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(5, 5, 5)
                .addComponent(jbBuscar))
        );

        jbCancelar.setFont(new java.awt.Font("Arial", 1, 12));
        jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_cancel.png"))); // NOI18N
        jbCancelar.setMnemonic('C');
        jbCancelar.setText("CERRAR");
        jbCancelar.setToolTipText("Cancelar la Operacion");
        jbCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCancelarActionPerformed(evt);
            }
        });
        jbCancelar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbCancelarKeyPressed(evt);
            }
        });

        jbDetalles.setFont(new java.awt.Font("Arial", 1, 12));
        jbDetalles.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/view_detailed.png"))); // NOI18N
        jbDetalles.setMnemonic('D');
        jbDetalles.setText("VISUALIZAR");
        jbDetalles.setToolTipText("Cancelar la Operacion");
        jbDetalles.setEnabled(false);
        jbDetalles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbDetallesActionPerformed(evt);
            }
        });

        jbAnular.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jbAnular.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/apps/preferences_web_browser_adblock.png"))); // NOI18N
        jbAnular.setText("ANULAR");
        jbAnular.setEnabled(false);
        jbAnular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAnularActionPerformed(evt);
            }
        });

        jbModificar.setFont(new java.awt.Font("Arial", 1, 12));
        jbModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/edit.png"))); // NOI18N
        jbModificar.setText("MODIFICAR");
        jbModificar.setEnabled(false);
        jbModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbModificarActionPerformed(evt);
            }
        });

        jbComprobante.setFont(new java.awt.Font("Arial", 1, 12));
        jbComprobante.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/view_detailed.png"))); // NOI18N
        jbComprobante.setMnemonic('D');
        jbComprobante.setText("COMPROBANTES");
        jbComprobante.setToolTipText("Cancelar la Operacion");
        jbComprobante.setEnabled(false);
        jbComprobante.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbComprobanteActionPerformed(evt);
            }
        });

        jbEnvio.setFont(new java.awt.Font("Arial", 1, 12));
        jbEnvio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/mail_send.png"))); // NOI18N
        jbEnvio.setText("ENVIAR");
        jbEnvio.setEnabled(false);
        jbEnvio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbEnvioActionPerformed(evt);
            }
        });

        jbtImprimir.setFont(new java.awt.Font("Arial", 1, 12));
        jbtImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/document_print.png"))); // NOI18N
        jbtImprimir.setText("IMPRIMIR");
        jbtImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtImprimirActionPerformed(evt);
            }
        });
        jbtImprimir.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbtImprimirKeyPressed(evt);
            }
        });

        jbFinalizar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jbFinalizar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/dialog_ok.png"))); // NOI18N
        jbFinalizar.setText("FINALIZAR");
        jbFinalizar.setEnabled(false);
        jbFinalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbFinalizarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 695, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jpOperativo, javax.swing.GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(38, 38, 38)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jbtImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(5, 5, 5)
                                    .addComponent(jbComprobante)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jbFinalizar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jbDetalles)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jbAnular, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jbModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jbCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jbEnvio)))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbAnular, jbCancelar, jbComprobante, jbDetalles, jbEnvio, jbModificar, jbtImprimir});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpOperativo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jbDetalles)
                    .addComponent(jbAnular)
                    .addComponent(jbModificar)
                    .addComponent(jbEnvio))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jbtImprimir)
                    .addComponent(jbComprobante)
                    .addComponent(jbFinalizar)
                    .addComponent(jbCancelar))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jcboMesKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcboMesKeyPressed

      /*  if (evt.getKeyCode() == KeyEvent.VK_ENTER ){
            this.jbBuscar.requestFocus();
        }*/
}//GEN-LAST:event_jcboMesKeyPressed

    private void jcboZonaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcboZonaKeyPressed
       
      /*  if (evt.getKeyCode() == KeyEvent.VK_ENTER ){
            this.jcboAno.requestFocus();
        }*/
}//GEN-LAST:event_jcboZonaKeyPressed

    private void jbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBuscarActionPerformed
      buscar();
}//GEN-LAST:event_jbBuscarActionPerformed

    private void jbBuscarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbBuscarKeyPressed
       
      /*  if (evt.getKeyCode() == KeyEvent.VK_ENTER ){
            this.jbBuscar.doClick();
        }*/
}//GEN-LAST:event_jbBuscarKeyPressed

    private void jtfRazonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfRazonActionPerformed

        buscarRazonSocial();
       // this.jcboFormaPago.requestFocus();
}//GEN-LAST:event_jtfRazonActionPerformed

    private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed
       
        this.dispose();
}//GEN-LAST:event_jbCancelarActionPerformed

    private void jbCancelarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbCancelarKeyPressed
       
}//GEN-LAST:event_jbCancelarKeyPressed

    private void jtfRazonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfRazonKeyPressed
        if (this.jtfRuc.getText().trim().length() > 0)
            this.jtfRuc.setText("");
    }//GEN-LAST:event_jtfRazonKeyPressed

    private void jtfRucActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfRucActionPerformed
          if (this.jtfRuc.getText().trim().length() < 1)
            this.jtfRazon.requestFocus();
        else
            buscarRazonSocial();
    }//GEN-LAST:event_jtfRucActionPerformed

    private void jbDetallesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbDetallesActionPerformed
        String nro_orden = "";
         int filaElegida = this.jtOrdenes.getSelectedRow();

     if (filaElegida < 0) {
          Utiles_MensajesDialogo.mensajeError("Debe elegir una Orden!");
          this.jtOrdenes.requestFocus();
          return;
      }

        try {
            nro_orden = this.jtOrdenes.getValueAt(filaElegida, 0).toString().trim();
            TipoTO tipo_orden = Listas.getTipo_porId(this.id_tipo_orden);
            if(tipo_orden.getDescripcion_valor().equalsIgnoreCase("COMPRA"))
                Reportes.verOrden(nro_orden);
            else
                Reportes.verOrdenServicio(nro_orden);

        } catch (Exception e) {
            e.printStackTrace();
          Utiles_MensajesDialogo.mensajeError("No se pudo Cargar la Orden\n" + e.getMessage());
        }
    }//GEN-LAST:event_jbDetallesActionPerformed

    private void jcboTipoOrdenItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcboTipoOrdenItemStateChanged
        this.id_tipo_orden = ((TipoTO)this.jcboTipoOrden.getSelectedItem()).getId_tabla_tipo();
    }//GEN-LAST:event_jcboTipoOrdenItemStateChanged

    private void jbAnularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAnularActionPerformed
        
         int filaElegida = this.jtOrdenes.getSelectedRow();

     if (filaElegida < 0) {
          Utiles_MensajesDialogo.mensajeError("Debe elegir una Orden!");
          this.jtOrdenes.requestFocus();
          return;
      }

        try {
            
            OrdenTO orden = (OrdenTO)this.ordenes_encontradas.get(this.jtOrdenes.convertRowIndexToModel(filaElegida));
           // List<TipoTO> tipos_orden = Listas.getTipo_porTabla("Tipo_Estado_Orden");
            TipoTO tipo = Listas.getTipo_porTablaYCodigo("Tipo_Estado_Orden", "NA");
            TipoTO tipo_anulado = Listas.getTipo_porTablaYCodigo("Tipo_Estado_Orden", "AN");
        //    for(TipoTO to : tipos_orden){
          //      if(to.getId_tabla_tipo() == orden.getEstado()){

                    if(tipo.getId_tabla_tipo() == orden.getEstado() ){
                         int res = javax.swing.JOptionPane.showConfirmDialog( this,"Esta seguro de Anular la Orden?",
                                         "Confirmar",javax.swing.JOptionPane.YES_NO_OPTION );
                        if(res==javax.swing.JOptionPane.YES_OPTION){
                                    if(GestionPedidosDelegate.getInstance().anularOrden(orden.getNroOrden())){
                                        orden.setEstado(tipo_anulado.getId_tabla_tipo());
                                        orden.setDescripcion_estado(tipo_anulado.getDescripcion_valor());
                                        Utiles_MensajesDialogo.mensajeExito();
                                        actualizaTablaDetallesSolicitud(ordenes_encontradas);
                                    }
                                    else
                                        Utiles_MensajesDialogo.mensajeError("No se pudo Anular la Orden");
                        }
                    }
                    else{
                        Utiles_MensajesDialogo.mensajeError("No se admite anular esta Orden");
                    }
        //            break;
         //       }
        //    }


        } catch (Exception e) {
            e.printStackTrace();
            Utiles_MensajesDialogo.mensajeError("No se pudo Cargar la Orden\n" + e.getMessage());
        }
    }//GEN-LAST:event_jbAnularActionPerformed

    private void jbModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbModificarActionPerformed
       int filaElegida = this.jtOrdenes.getSelectedRow();

     if (filaElegida < 0) {
          Utiles_MensajesDialogo.mensajeError("Debe elegir una Orden!");
          this.jtOrdenes.requestFocus();
          return;
      }

        try {

            OrdenTO orden = (OrdenTO)this.ordenes_encontradas.get(this.jtOrdenes.convertRowIndexToModel(filaElegida));
           // if(orden.getNro_solicitud_cotizacion().length()==0 && orden.getNro_licitacion().length()==0){
                //modificar orden
                jifRegistrarOrdenCompra modificarOrden=new jifRegistrarOrdenCompra(false);
                modificarOrden.setOrdenEdit(orden);
                modificarOrden.setLocation(this.dsk_padre.getWidth()/2 - modificarOrden.getWidth()/2 ,this.dsk_padre.getHeight()/2 - modificarOrden.getHeight()/2 - 20);
                this.dsk_padre.getDesktop().add( modificarOrden, javax.swing.JLayeredPane.DRAG_LAYER);
                modificarOrden.show();
                try {
                    modificarOrden.setSelected(true);
                } catch (java.beans.PropertyVetoException e2) {}
           //     }
           // else
           //     Utiles_MensajesDialogo.mensajeError("No se admite modificar esta Orden");
        } catch (Exception e) {
            e.printStackTrace();
            Utiles_MensajesDialogo.mensajeError("No se pudo Cargar la Orden\n" + e.getMessage());
        }
    }//GEN-LAST:event_jbModificarActionPerformed

    private void jbComprobanteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbComprobanteActionPerformed
         int filaElegida = this.jtOrdenes.getSelectedRow();

     if (filaElegida < 0) {
          Utiles_MensajesDialogo.mensajeError("Debe elegir una Orden!");
          this.jtOrdenes.requestFocus();
          return;
      }


        OrdenTO orden = (OrdenTO)this.ordenes_encontradas.get(this.jtOrdenes.convertRowIndexToModel(filaElegida));

         Frame frm = JOptionPane.getFrameForComponent((JInternalFrame)this);
         jdVerDocumentos panel = new jdVerDocumentos(frm,true,orden.getNroOrden());
         panel.setTitle("DOCUMENTOS DE ORDEN");
         panel.setLocationRelativeTo(null);
         panel.setVisible(true);

}//GEN-LAST:event_jbComprobanteActionPerformed

    private void jbEnvioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbEnvioActionPerformed
        int filaElegida = this.jtOrdenes.getSelectedRow();

         if (filaElegida < 0) {
              Utiles_MensajesDialogo.mensajeError("Debe elegir una Orden!");
              this.jtOrdenes.requestFocus();
              return;
          }

         if (filaElegida < 0) {
              Utiles_MensajesDialogo.mensajeError("Debe elegir una Orden!");
              this.jtOrdenes.requestFocus();
              return;
          }

         OrdenTO orden = (OrdenTO)this.ordenes_encontradas.get(this.jtOrdenes.convertRowIndexToModel(filaElegida));

        try {
            if(GestionPedidosDelegate.getInstance().generaDocumentoAEmail(orden.getNroOrden(), this.id_tipo_orden, orden.getRuc_proveedor()))
                Utiles_MensajesDialogo.mensajeExito();
           // this.jbEnvio.setEnabled(false);
        } catch (EmailVacioException ex) {
            Utiles_MensajesDialogo.mensajeError(ex.getMessage());
        } catch (Exception ex) {
            Utiles_MensajesDialogo.mensajeError(ex.getMessage());
        }
}//GEN-LAST:event_jbEnvioActionPerformed

    private void jbtImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtImprimirActionPerformed
       MiTablePrint pp = new MiTablePrint(this.jtOrdenes, "ORDENES", "ORDENES DE COMPRA");
        pp.showPrintPreview();
}//GEN-LAST:event_jbtImprimirActionPerformed

    private void jbtImprimirKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbtImprimirKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER ){
            this.jbtImprimir.doClick();
        }
}//GEN-LAST:event_jbtImprimirKeyPressed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        if(this.jCheckBox1.isSelected()){
            this.jcbEmpresa.setEnabled(true);
        } else{
            this.jcbEmpresa.setEnabled(false);
        }
        this.llenarComboEmpresa();
        //this.intelliHintsProyectos.setCompletionList(Listas.obtenerProyectosPorEmpresa(((EmpresaTO)this.jcbEmpresa.getSelectedItem()).getRuc()));
}//GEN-LAST:event_jCheckBox1ActionPerformed

    private void jcboAnoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcboAnoKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER ){
            this.jcboMes.requestFocus();
        }
    }//GEN-LAST:event_jcboAnoKeyPressed

    private void jcboAnoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboAnoActionPerformed
        llenarComboMes();
    }//GEN-LAST:event_jcboAnoActionPerformed

    private void jtfNroOrdenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfNroOrdenActionPerformed

}//GEN-LAST:event_jtfNroOrdenActionPerformed

    private void jbFinalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbFinalizarActionPerformed
         int filaElegida = this.jtOrdenes.getSelectedRow();

     if (filaElegida < 0) {
          Utiles_MensajesDialogo.mensajeError("Debe elegir una Orden!");
          this.jtOrdenes.requestFocus();
          return;
      }

        try {

            OrdenTO orden = (OrdenTO)this.ordenes_encontradas.get(this.jtOrdenes.convertRowIndexToModel(filaElegida));
           // List<TipoTO> tipos_orden = Listas.getTipo_porTabla("Tipo_Estado_Orden");
            TipoTO tipo = Listas.getTipo_porTablaYCodigo("Tipo_Estado_Orden", "PA");
            TipoTO tipo_finalizado = Listas.getTipo_porTablaYCodigo("Tipo_Estado_Orden", "TA");
        //    for(TipoTO to : tipos_orden){
          //      if(to.getId_tabla_tipo() == orden.getEstado()){

                    if(tipo.getId_tabla_tipo() == orden.getEstado() ){
                         int res = javax.swing.JOptionPane.showConfirmDialog( this,"Esta seguro de Finalizar la Orden?",
                                         "Confirmar",javax.swing.JOptionPane.YES_NO_OPTION );
                        if(res==javax.swing.JOptionPane.YES_OPTION){
                                    if(GestionPedidosDelegate.getInstance().finalizarOrden(orden.getNroOrden())){
                                        orden.setEstado(tipo_finalizado.getId_tabla_tipo());
                                        orden.setDescripcion_estado(tipo_finalizado.getDescripcion_valor());
                                        Utiles_MensajesDialogo.mensajeExito();
                                        actualizaTablaDetallesSolicitud(ordenes_encontradas);
                                    }
                                    else
                                        Utiles_MensajesDialogo.mensajeError("No se pudo Finalizar la Orden");
                        }
                    }
                    else{
                        Utiles_MensajesDialogo.mensajeError("No se admite finalizar esta Orden");
                    }
        //            break;
         //       }
        //    }


        } catch (Exception e) {
            e.printStackTrace();
            Utiles_MensajesDialogo.mensajeError("No se pudo Cargar la Orden\n" + e.getMessage());
        }
    }//GEN-LAST:event_jbFinalizarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel Mes;
    private administracion.BeanBinding.CboBeanBindingAno cboBeanBindingAno1;
    private administracion.BeanBinding.CboBeanBindingEmpresa cboBeanBindingEmpresa1;
    private administracion.BeanBinding.CboBeanBindingMes cboBeanBindingMes1;
    private administracion.BeanBinding.CboBeanBindingTipo cboBeanBindingTipo1;
    private administracion.BeanBinding.CboBeanBindingZona cboBeanBindingZona1;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbAnular;
    private javax.swing.JButton jbBuscar;
    private javax.swing.JButton jbCancelar;
    private javax.swing.JButton jbComprobante;
    private javax.swing.JButton jbDetalles;
    private javax.swing.JButton jbEnvio;
    private javax.swing.JButton jbFinalizar;
    private javax.swing.JButton jbModificar;
    private javax.swing.JButton jbtImprimir;
    private javax.swing.JComboBox jcbEmpresa;
    private javax.swing.JComboBox jcboAno;
    private javax.swing.JComboBox jcboMes;
    private javax.swing.JComboBox jcboTipoOrden;
    private javax.swing.JComboBox jcboZona;
    private javax.swing.JPanel jpOperativo;
    private javax.swing.JTable jtOrdenes;
    private javax.swing.JTextField jtfNroOrden;
    private javax.swing.JTextField jtfRazon;
    private javax.swing.JTextField jtfRuc;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

}
